import axios from 'axios'
const state = {
  productInfos: []
}
const getters = {
  // 总数
  getCount (state) {
    return state.productInfos.reduce((sum, item) => sum + item.count, 0)
  },
  // 总价
  getSum (state) {
    return state.productInfos.reduce((sum, item) => sum + item.count * item.price, 0)
  }
}
const mutations = {
  changeCount (state, newP) {
    state.productInfos.forEach(item => {
      if (item.id === newP.id) {
        item.count += newP.num
      }
    })
  },
  setProductInfos (state, newProducts) {
    console.log('设置值')
    state.productInfos = newProducts
  },
  setCountById (state, payload) {
    state.productInfos.forEach(item => { if (item.id === payload.id) { item.count = payload.count } })
  }
}
const actions = {
  async getList (context) {
    console.log('异步获取数据列表')
    const res = await axios.get('http://localhost:3000/productInfos')
    context.commit('setProductInfos', res.data)
  },
  async changePCount (context, payload) {
    // 修改后台数量
    await axios.patch('http://localhost:3000/productInfos/' + payload.id, {
      count: payload.count
    })
    // 修改全局数量
    context.commit('setCountById', payload)
  }

}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
